import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:ride_rex/article/post/article_post_logic.dart';
import 'package:ride_rex/article/post/article_post_page.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:ride_rex/login/login_logic.dart';
import 'package:ride_rex/main/home/home_logic.dart';
import 'package:ride_rex/main/home/landmark_bean.dart';
import 'package:ride_rex/net/common_net.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../coin_shop/coin_shop_page.dart';
import '../route.dart';
import '../service/user_service.dart';
import '../standard/app_colors.dart';

class CommonDialogs {
  /// 登录弹窗
  static void showLoginDialog() {
    oneButton(
      description: 'Login expired, please log in again',
      confirmTitle: 'Login',
      keepSingle: true,
      onConfirm: () {
        LogoutLogic.logout();
        CommonRoute.openLogin();
      },
    );
  }

  static void showPrivacy({VoidCallback? onConfirm}) {
    SmartDialog.show(
      builder: (context) {
        List<Widget> children = [];

        ///图标
        children.add(
          ClipRRect(
            borderRadius: BorderRadius.circular(12.w),
            child: Image.asset(
              Assets.iconsIconSmall,
              width: 64.w,
            ).paddingTop(20.w),
          ),
        );

        /// 标题
        children.addAll([
          const TextWidget.moreLine(text: 'RideRex', fontSize: 14, color: AppColors.text).paddingTop(10.w),
        ]);

        /// 描述
        children.add(Text.rich(
          TextSpan(
            text: 'By using our App you agree with our ',
            children: [
              TextSpan(
                text: 'Term of Use',
                style: const TextStyle(color: AppColors.primary),
                recognizer: TapGestureRecognizer()..onTap = CommonRoute.openProtocolPage,
              ),
              const TextSpan(text: ' and '),
              TextSpan(
                text: 'Privacy Policy.',
                style: const TextStyle(color: AppColors.primary),
                recognizer: TapGestureRecognizer()..onTap = CommonRoute.openPrivacyPage,
              ),
            ],
          ),
          style: const TextStyle(color: AppColors.text, fontSize: 14, height: 1.5),
        ).paddingTop(26.w));

        return Container(
          width: ScreenUtil().screenWidth - 30.w * 2,
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18.w)),
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ...children,
              ButtonWidget.text(
                'Agree and Continue',
                textColor: Colors.white,
                borderRadius: 12.w,
                width: 180.w,
                height: 40.w,
                fontSize: 14,
                fontWeight: FontWeight.bold,
                alignment: Alignment.center,
                gradient: AppColors.primaryGradient,
                onTap: () async {
                  await SmartDialog.dismiss();
                  onConfirm?.call();
                },
              ).paddingTop(24.w),
              ButtonWidget.text(
                'Cancel',
                textColor: '#A9A9A9'.toColor,
                borderRadius: 12.w,
                width: 180.w,
                height: 40.w,
                fontSize: 14,
                fontWeight: FontWeight.bold,
                alignment: Alignment.center,
                backgroundColor: '#F4F4F4'.toColor,
                onTap: () async {
                  await SmartDialog.dismiss();
                },
              ).paddingOnly(top: 20.w, bottom: 24.w),
            ],
          ),
        );
      },
      backDismiss: false,
      clickMaskDismiss: false,
      tag: 'privacy',
    );
  }

  static Future showMedal(LandmarkBean bean) async {
    await SmartDialog.show(
      builder: (context) {
        return _MedalDialog(bean);
      },
      backDismiss: false,
      clickMaskDismiss: false,
      tag: 'medal',
    );
  }

  static void closeMedal() {
    SmartDialog.dismiss(tag: 'medal');
  }

  static void oneButton({
    String? title,
    String description = '',
    String? confirmTitle,
    VoidCallback? onConfirm,
    String? tag,
    VoidCallback? onDismiss,
    bool keepSingle = false,
  }) {
    SmartDialog.show(
      // keepSingle: true,
      builder: (context) {
        String titleStr = title ?? 'Tips';
        return Container(
          width: ScreenUtil().screenWidth - 30.w,
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8.w)),
          padding: EdgeInsets.fromLTRB(20.w, 15.w, 20.w, 25.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (titleStr.notEmpty) ...[
                TextWidget.moreLine(text: titleStr, fontSize: 18, color: Colors.black),
                SizedBox(height: 20.w),
              ],
              if (description.notEmpty) ...[
                TextWidget.moreLine(text: description, fontSize: 15, color: Colors.black),
                SizedBox(height: 25.w),
              ],
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 7.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: ButtonWidget.text(
                        confirmTitle ?? 'Confirm',
                        textColor: Colors.white,
                        borderColor: Colors.transparent,
                        backgroundColor: AppColors.primary,
                        borderWidth: 0.5,
                        borderRadius: 45.w,
                        height: 45.w,
                        alignment: Alignment.center,
                        onTap: () async {
                          await SmartDialog.dismiss();
                          onConfirm?.call();
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
      backDismiss: false,
      clickMaskDismiss: false,
      tag: tag,
      onDismiss: onDismiss,
      keepSingle: keepSingle,
    );
  }

  static void twoButton({
    String? title,
    String description = '',
    String? cancelTitle,
    String? confirmTitle,
    VoidCallback? onCancel,
    VoidCallback? onConfirm,
    Widget? descriptionWidget,
    String? tag,
    VoidCallback? onDismiss,
  }) {
    SmartDialog.show(
      builder: (context) {
        List<Widget> children = [];

        String titleStr = title ?? 'Tips';

        /// 标题
        if (titleStr.notEmpty) {
          children.addAll([
            TextWidget.moreLine(text: titleStr, fontSize: 16, color: '3D3D3D'.toColor, fontWeight: FontWeight.bold),
            SizedBox(height: 30.w),
          ]);
        }

        /// 描述
        if (descriptionWidget != null) {
          children.addAll([
            descriptionWidget,
            SizedBox(height: 25.w),
          ]);
        } else {
          if (description.notEmpty) {
            children.addAll([
              TextWidget.moreLine(text: description, fontSize: 14, color: Colors.black),
              SizedBox(height: 25.w),
            ]);
          }
        }

        return Container(
          width: ScreenUtil().screenWidth - 24.w * 2,
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12.w)),
          padding: EdgeInsets.fromLTRB(20.w, 30.w, 20.w, 20.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (children.isNotEmpty) ...children,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  ButtonWidget.text(
                    'Cancel',
                    textColor: const Color(0XFF4E5969),
                    borderColor: AppColors.fill,
                    borderWidth: 1,
                    borderRadius: 42.w,
                    width: 134.w,
                    height: 42.w,
                    fontSize: 16,
                    alignment: Alignment.center,
                    onTap: () async {
                      await SmartDialog.dismiss();
                      onCancel?.call();
                    },
                  ),
                  ButtonWidget.text(
                    'Confirm',
                    textColor: Colors.white,
                    borderColor: Colors.transparent,
                    backgroundColor: AppColors.primary,
                    borderWidth: 1,
                    borderRadius: 42.w,
                    width: 134.w,
                    height: 42.w,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    alignment: Alignment.center,
                    onTap: () async {
                      await SmartDialog.dismiss();
                      onConfirm?.call();
                    },
                  ),
                ],
              ),
            ],
          ),
        );
      },
      backDismiss: false,
      clickMaskDismiss: false,
      tag: tag,
      onDismiss: onDismiss,
    );
  }
}

class _MedalDialog extends StatefulWidget {
  const _MedalDialog(this.bean);

  final LandmarkBean bean;

  @override
  State<_MedalDialog> createState() => _MedalDialogState();
}

class _MedalDialogState extends State<_MedalDialog> {
  final ValueNotifier<bool> flag = ValueNotifier(false);

  @override
  void initState() {
    super.initState();
    CommonObservable().addObserver(ArticlePostLogic.keyListener, refresh);
  }

  void refresh(key, [value]) {
    if (widget.bean.landmarkId.equals(value)) {
      update();
    }
  }

  @override
  void dispose() {
    super.dispose();
    CommonObservable().removeObserver(ArticlePostLogic.keyListener, refresh);
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: flag,
      builder: (BuildContext context, bool value, Widget? child) {
        ///需要支付
        bool needPay = (widget.bean.coin ?? 0) > 0;

        ///已解锁
        bool isUnlocked = widget.bean.unlock == 1;
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              height: 440.w,
              width: 343.w,
              decoration: CommonDecoration.getShapeDecoration(
                image: const DecorationImage(image: AssetImage(Assets.pngHomeDialogBg)),
                radius: 24.w,
                borderColor: Colors.transparent,
                borderWidth: 1,
              ),
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  Column(
                    children: [
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          _buildTopBg(),
                          _buildMedal().positioned(top: 0, right: 0),
                          if (!isUnlocked) _buildCover().positioned(top: 0, left: 0, right: 0, bottom: 0), //未解锁
                          if (!isUnlocked && !needPay) _buildLockWhite(), //未解锁 且 不需要支付
                          if (!isUnlocked && needPay) _buildCoin().positioned(left: 8.w, bottom: 8.w), //未解锁 且 需要支付
                        ],
                      ).padding(top: 10.w, left: 16.w, right: 16.w),
                      _buildDescription().padding(top: 12.w, left: 16.w, right: 16.w),
                    ],
                  ),
                  if (!isUnlocked && needPay) _buildUnlock().positioned(bottom: 74.w), //未解锁 且 需要支付
                  if (isUnlocked || (!isUnlocked && !needPay))
                    _buildButton().positioned(bottom: 64.w), //已解锁 或 (未解锁 且 不需要支付)
                  if (!isUnlocked) _buildTips().positioned(left: 25.w, right: 25.w, bottom: 32.w), //未解锁
                ],
              ),
            ),
            _buildClose().paddingTop(16.w),
          ],
        ).width(343.w);
      },
    );
  }

  Widget _buildClose() => ButtonWidget(
        onTap: CommonDialogs.closeMedal,
        child: IconWidget.image(Assets.pngHomeDialogClose, size: 30.w),
      );

  Widget _buildTopBg() {
    return SizedBox(
      height: 150.w,
      child: FractionallySizedBox(
        widthFactor: 1,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16.w),
          child: IconWidget.image('assets/png/${widget.bean.medalBg}.jpg', fit: BoxFit.cover),
        ),
      ),
    );
  }

  Widget _buildCover() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(bg: Colors.black.withOpacity(0.4), radius: 16.w),
    );
  }

  Widget _buildLockWhite() => Assets.svgLockGreen.toSvg(width: 30.w, color: Colors.white);

  Widget _buildMedal() {
    return Container(
      width: 70.w,
      height: 48.w,
      alignment: Alignment.center,
      decoration: CommonDecoration.getRadius(
        bg: Colors.black.withOpacity(0.4),
        topRight: 16.w,
        bottomLeft: 16.w,
      ),
      child: IconWidget.image('assets/png/${widget.bean.medalIcon}.png', size: 40.w),
    );
  }

  Widget _buildCoin() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(
        radius: 24.w,
        gradient: const LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          stops: [0, 1],
          colors: [Color(0XFFF0FAFF), Color(0XFFE7FFF7)],
        ),
      ),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 3.w),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          IconWidget.image(Assets.pngMyCoin, width: 24.w, height: 19.w).paddingRight(7.w),
          TextWidget.oneLine(text: '\$${widget.bean.coin ?? 0}', fontSize: 16, color: AppColors.text),
        ],
      ),
    );
  }

  Widget _buildDescription() {
    return TextWidget.moreLine(
      text: widget.bean.description,
      maxLines: 4,
      fontSize: 16,
      color: AppColors.text,
      textAlign: TextAlign.center,
    );
  }

  Widget _buildUnlock() => ButtonWidget(
        hasInkWell: false,
        onTap: unlock,
        child: IconWidget.image(Assets.pngHomeDialogLock, size: 82.w),
      );

  Widget _buildButton() {
    return ButtonWidget.text(
      widget.bean.unlock == 0 ? 'To Unlock' : 'OK',
      textColor: Colors.white,
      borderRadius: 20.w,
      width: 180.w,
      height: 38.w,
      fontSize: 16,
      fontWeight: FontWeight.bold,
      alignment: Alignment.center,
      gradient: AppColors.primaryGradient,
      borderWidth: 2.w,
      borderColor: Colors.white,
      onTap: unlock,
    );
  }

  void unlock() async {
    if (widget.bean.unlock != 0) {
      CommonDialogs.closeMedal();
      return;
    }

    int outlay = widget.bean.coin ?? 0;

    if (outlay > 0) {
      Loading.show();
      await ApiHome.unlockLandmark(outlay: outlay).post().then((value) {
        UserService.instance.getCacheMineInfoBean(true);
        update();
      }).catchError((e) {
        Future.delayed(const Duration(seconds: 1), () {
          CommonRoute.open(const CoinShopPage());
        });
      }).whenComplete(() {
        Loading.dismiss();
      });
    } else {
      CommonRoute.open(ArticlePostPage(landmarkId: widget.bean.landmarkId));
    }
  }

  void update() {
    widget.bean.unlock = 1;
    CommonObservable().publishChange(HomeLogic.keyListener, widget.bean);
    flag.value = !flag.value;
  }

  Widget _buildTips() {
    return TextWidget.moreLine(
      text: widget.bean.coin == 0
          ? 'You can unlock it by publishing an article.'
          : 'You need to spend 99 gold coins to unlock this landmark.',
      fontSize: 12,
      color: '#0A202A'.toColor.withOpacity(0.4),
      textAlign: TextAlign.center,
    );
  }
}
